<template>
  <div class="app-container">
    <!-- 左侧树形菜单 -->
    <div class="tree-panel">
      <div class="head-container">
        <el-input
          v-model="projectName"
          placeholder="请输入培训项目"
          clearable
          size="small"
          prefix-icon="el-icon-search"
          style="margin-bottom: 20px"
          @keyup.enter.native="filterTree"
        />
      </div>
      <el-tree
        ref="tree"
        :data="projectOptions"
        :props="defaultProps"
        :expand-on-click-node="false"
        :filter-node-method="filterNode"
        node-key="id"
        default-expand-all
        highlight-current
        @node-click="handleNodeClick"
      />
    </div>

    <el-col :span="20" style="padding: 20px">
      <!-- 搜索区域 -->
      <el-form
        :model="queryParams"
        inline
        size="small"
        v-show="showSearch"
        label-width="100px"
      >
        <el-row :gutter="20">
          <!-- 姓名 -->
          <el-col :span="6">
            <el-form-item label="姓名">
              <el-input
                v-model="queryParams.studentName"
                placeholder="请输入姓名"
                clearable
                @keyup.enter.native="handleQuery"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>

          <!-- 手机号码 -->
          <el-col :span="6">
            <el-form-item label="手机号码">
              <el-input
                v-model="queryParams.phonenumber"
                placeholder="请输入手机号码"
                clearable
                @keyup.enter.native="handleQuery"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>

          <!-- 证件编号 -->
          <el-col :span="6">
            <el-form-item label="证件编号">
              <el-input
                v-model="queryParams.idNumber"
                placeholder="请输入证件编号"
                clearable
                @keyup.enter.native="handleQuery"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>

          <!-- 证书编号 -->
          <el-col :span="6">
            <el-form-item label="证书编号">
              <el-input
                v-model="queryParams.certificateNo"
                placeholder="请输入证书编号"
                clearable
                @keyup.enter.native="handleQuery"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>

          <!-- 单位名称 -->
          <el-col :span="6">
            <el-form-item label="单位名称">
              <el-input
                v-model="queryParams.unitName"
                placeholder="请输入单位名称"
                clearable
                @keyup.enter.native="handleQuery"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>

          <!-- 发放时间 -->
          <el-col :span="6">
            <el-form-item label="发放时间">
              <el-date-picker
                v-model="queryParams.issueTimeRange"
                type="daterange"
                range-separator="-"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                value-format="yyyy-MM-dd"
                clearable
                style="width: 210px"
              />
            </el-form-item>
          </el-col>

          <!-- 有效期起 -->
          <el-col :span="6">
            <el-form-item label="有效期起">
              <el-date-picker
                v-model="queryParams.validStart"
                type="daterange"
                range-separator="-"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                value-format="yyyy-MM-dd"
                clearable
                style="width: 210px"
              />
            </el-form-item>
          </el-col>

          <!-- 有效期止 -->
          <el-col :span="6">
            <el-form-item label="有效期止">
              <el-date-picker
                v-model="queryParams.validEnd"
                type="daterange"
                range-separator="-"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                value-format="yyyy-MM-dd"
                clearable
                style="width: 210px"
              />
            </el-form-item>
          </el-col>

          <!-- 电子证书状态 -->
          <el-col :span="6">
            <el-form-item label="电子证书">
              <el-select
                v-model="queryParams.digitalStatus"
                placeholder="选择电子证书状态"
                clearable
                style="width: 100%"
              >
                <el-option
                  v-for="dict in dict.type.digital_status"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </el-form-item>
          </el-col>

          <!-- 纸质证书状态 -->
          <el-col :span="6">
            <el-form-item label="纸质证书">
              <el-select
                v-model="queryParams.paperStatus"
                placeholder="选择纸质证书状态"
                clearable
                style="width: 100%"
              >
                <el-option
                  v-for="dict in dict.type.paper_status"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </el-form-item>
          </el-col>

          <!-- 备注 -->
          <el-col :span="6">
            <el-form-item label="备注">
              <el-input
                v-model="queryParams.remark"
                placeholder="请输入备注"
                clearable
                @keyup.enter.native="handleQuery"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>

          <!-- 操作按钮 -->
          <el-col :span="6">
            <el-form-item style="float: right; margin-right: 50px">
              <el-button
                type="primary"
                icon="el-icon-search"
                @click="handleQuery"
                >搜索</el-button
              >
              <el-button icon="el-icon-refresh" @click="resetQuery"
                >重置</el-button
              >
            </el-form-item>
          </el-col>

          <!-- 证书类型 -->
          <el-col :span="6">
            <el-form-item label-width="100px" label="证书类型">
              <el-select
                v-model="queryParams.certificateType"
                placeholder="选择证书类型"
                clearable
                style="width: 100%"
              >
                <el-option
                  v-for="dict in dict.type.certificate_type"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </el-form-item>
          </el-col>

          <!-- 证书状态 -->
          <el-col :span="6">
            <el-form-item label="证书状态">
              <el-select
                v-model="queryParams.certificateStatus"
                placeholder="选择证书状态"
              >
                <el-option
                  v-for="dict in dict.type.expire_reminder_days"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <el-row :gutter="10" class="mb8">
        <!-- 按钮组 -->
        <el-col :span="10">
          <div
            style="
              display: flex;
              justify-content: space-between;
              align-items: center;
              padding: 10px 0;
            "
          >
            <!-- 左侧按钮 -->
            <div style="display: flex">
              <span class="group-label">管理列表</span>
              <el-button size="medium" @click="handleExport">导出</el-button>
              <el-button size="medium" @click="handleRemark">备注</el-button>
              <el-button size="medium" @click="notifyStudent" :disabled="ids.length ===0"
                >通知学员</el-button
              >
            </div>
          </div>
        </el-col>
        <el-col :span="14">
          <div style="display: flex; padding: 10px 0; float: left">
            <span class="group-label">复训换证</span>
            <el-button size="medium" @click="handleRenewalApply"
              >报名复训换证</el-button
            >
          </div>

          <!-- 右侧按钮 -->
          <div style="display: flex; float: right">
            <column-config-dialog-vue
              :showSearch.sync="showSearch"
              :columns="tableColumns"
              @queryTable="getList"
            ></column-config-dialog-vue>
          </div>
        </el-col>

        <!-- 第二行 -->
        <el-col :span="10">
          <div style="display: flex; padding: 10px 0; float: left">
            <span class="group-label">报名信息</span>
            <el-button size="medium" @click="handleView">查看详情</el-button>
            <el-button size="medium" @click="handleEdit">修改</el-button>
            <el-button size="medium" @click="handleDelete">删除</el-button>
          </div>
        </el-col>
        <el-col :span="14">
          <div style="display: flex; padding: 10px 0; float: left">
            <span class="group-label">电子证书</span>
            <el-button size="medium" @click="generateElectronicCertificate"
              >生成电子证书</el-button
            >
            <el-button size="medium" @click="revokeElectronicCertificate"
              >撤销电子证书</el-button
            >
            <el-button size="medium" @click="viewElectronicCertificate"
              >查看电子证书</el-button
            >
            <el-button size="medium" @click="downloadElectronicCertificate"
              >下载电子证书</el-button
            >
            <el-button size="medium" @click="sendElectronicCertificate"
              >发送电子证书</el-button
            >
          </div>
        </el-col>

        <!-- 第三行 -->
        <el-col :span="10">
          <div style="display: flex; padding: 10px 0; float: left">
            <span class="group-label">档案</span>
            <el-button size="medium" @click="handleExportTest1" >档案扫描</el-button>
            <el-button size="medium" @click="handleExportTest2"  :disabled="ids.length === 0">档案上传</el-button>
            <el-button size="medium" @click="handleExportTest2"  :disabled="ids.length === 0">档案查看</el-button>
            <el-button size="medium" @click="handleExportTest2"  :disabled="ids.length === 0">线上档案确认</el-button>
          </div>
        </el-col>
        <el-col :span="14">
          <div style="display: flex; padding: 10px 0; float: left">
            <span class="group-label">纸质证书</span>
            <el-button size="medium" @click="fastIssuePaperCertificate"
              >快递发放证书</el-button
            >
            <el-button size="medium" @click="onSitePickupCertificate"
              >现场领取证书</el-button
            >
          </div>
        </el-col>

        <!-- 第四行 -->
        <el-col :span="10">
          <div style="display: flex; padding: 10px 0; float: left">
            <span class="group-label">缴费</span>
            <el-button size="medium" @click="1">缴费二维码</el-button>
            <el-button size="medium" @click="handlePaymentMethodChange(2)"
              >转账缴费</el-button
            >
            <el-button size="medium" @click="handlePaymentMethodChange(3)"
              >现金缴费</el-button
            >
            <el-button size="medium" @click="handlePaymentMethodChange(4)"
              >POS机缴费</el-button
            >
          </div>
        </el-col>
        <el-col :span="7">
          <div style="display: flex; padding: 10px 0; float: left">
            <span class="group-label">退款</span>
            <el-button size="medium" @click="handleStartRefund"
              >发起退费</el-button
            >
            <el-button size="medium" @click="handleCancelRefund"
              >取消退费</el-button
            >
          </div>
        </el-col>
        <el-col :span="7">
          <div style="display: flex; padding: 10px 0; float: left">
            <span class="group-label">发票</span>
            <el-button size="medium" @click="1">查看发票</el-button>
            <el-button size="medium" @click="1">已预开票</el-button>
          </div>
        </el-col>
      </el-row>

      <!-- 表格 -->
      <el-table
        v-loading="loading"
        :data="certificateIssueList"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" align="center" />

        <!-- 证书类型 -->
        <el-table-column
          label="证书类型"
          align="center"
          prop="certificateType"
          v-if="
            tableColumns.find((col) => col.prop === 'certificateType').visible
          "
        >
          <template slot-scope="scope">
            {{
              dict.label.certificate_type[scope.row.certificateType] ||
              scope.row.certificateType
            }}
          </template>
        </el-table-column>

        <!-- 电子证书状态 -->
        <el-table-column
          label="电子证书状态"
          align="center"
          prop="digitalStatus"
          v-if="
            tableColumns.find((col) => col.prop === 'digitalStatus').visible
          "
        >
          <template slot-scope="scope">
            {{
              dict.label.digital_status[scope.row.digitalStatus] ||
              scope.row.digitalStatus
            }}
          </template>
        </el-table-column>

        <!-- 纸质证书状态 -->
        <el-table-column
          label="纸质证书状态"
          align="center"
          prop="paperStatus"
          v-if="tableColumns.find((col) => col.prop === 'paperStatus').visible"
        >
          <template slot-scope="scope">
            {{
              dict.label.paper_status[scope.row.paperStatus] ||
              scope.row.paperStatus
            }}
          </template>
        </el-table-column>
        <!-- 证书编号 -->
        <el-table-column
          label="证书编号"
          align="center"
          prop="certificateNo"
          v-if="
            tableColumns.find((col) => col.prop === 'certificateNo').visible
          "
        />

        <!-- 证件编号 -->
        <el-table-column
          label="编号"
          align="center"
          prop="idNumber"
          v-if="tableColumns.find((col) => col.prop === 'idNumber').visible"
        />

        <!-- 姓名 -->
        <el-table-column
          label="姓名"
          align="center"
          prop="studentName"
          v-if="tableColumns.find((col) => col.prop === 'studentName').visible"
        />

        <!-- 性别 -->
        <el-table-column
          label="性别"
          align="center"
          prop="sex"
          v-if="tableColumns.find((col) => col.prop === 'sex').visible"
        />

        <!-- 电话 -->
        <el-table-column
          label="电话"
          align="center"
          prop="phonenumber"
          v-if="tableColumns.find((col) => col.prop === 'phonenumber').visible"
        />

        <!-- 单位名称 -->
        <el-table-column
          label="单位名称"
          align="center"
          prop="unitName"
          v-if="tableColumns.find((col) => col.prop === 'unitName').visible"
        />

        <!-- 培训项目 -->
        <el-table-column
          label="培训项目"
          align="center"
          prop="projectName"
          v-if="tableColumns.find((col) => col.prop === 'projectName').visible"
        />

        <el-table-column
          label="报名来源"
          align="center"
          prop="registrationMethod"
          v-if="
            tableColumns.find((col) => col.prop === 'registrationMethod')
              .visible
          "
        />

        <el-table-column
          label="联系人"
          align="center"
          prop="contact"
          v-if="tableColumns.find((col) => col.prop === 'contact').visible"
        />

        <el-table-column
          label="联系人电话"
          align="center"
          prop="unitPhonenumber"
          v-if="
            tableColumns.find((col) => col.prop === 'unitPhonenumber').visible
          "
        />

        <el-table-column
          label="原证书有效期起"
          align="center"
          prop="originalValidityStart"
          v-if="
            tableColumns.find((col) => col.prop === 'originalValidityStart')
              .visible
          "
        />

        <el-table-column
          label="原证书有效期止"
          align="center"
          prop="originalValidityEnd"
          v-if="
            tableColumns.find((col) => col.prop === 'originalValidityEnd')
              .visible
          "
        />

        <el-table-column
          label="原证书编号"
          align="center"
          prop="originalCertificateNo"
          v-if="
            tableColumns.find((col) => col.prop === 'originalCertificateNo')
              .visible
          "
        />

        <el-table-column
          label="费用"
          align="center"
          prop="certificateReissueFee"
          v-if="
            tableColumns.find((col) => col.prop === 'certificateReissueFee')
              .visible
          "
        />

        <el-table-column
          label="缴费状态"
          align="center"
          prop="paymentState"
          v-if="tableColumns.find((col) => col.prop === 'paymentState').visible"
        />

        <el-table-column
          label="发票状态"
          align="center"
          prop="invoiceStatus"
          v-if="
            tableColumns.find((col) => col.prop === 'invoiceStatus').visible
          "
        />

        <el-table-column
          label="档案状态"
          align="center"
          prop="recordStatus"
          v-if="tableColumns.find((col) => col.prop === 'recordStatus').visible"
        />

        <el-table-column
          label="档案缺失情况"
          align="center"
          prop="recordMissing"
          v-if="
            tableColumns.find((col) => col.prop === 'recordMissing').visible
          "
        />

        <el-table-column
          label="提交状态"
          align="center"
          prop="submissionStatus"
          v-if="
            tableColumns.find((col) => col.prop === 'submissionStatus').visible
          "
        />

        <!-- 证书发放时间 -->
        <el-table-column
          label="证书发放时间"
          align="center"
          prop="issueTime"
          v-if="tableColumns.find((col) => col.prop === 'issueTime').visible"
        >
          <template slot-scope="scope">
            {{ scope.row.issueTime }}
          </template>
        </el-table-column>

        <!-- 证书有效期起 -->
        <el-table-column
          label="证书有效期起"
          align="center"
          prop="validStart"
          v-if="tableColumns.find((col) => col.prop === 'validStart').visible"
        />

        <!-- 证书有效期止 -->
        <el-table-column
          label="证书有效期止"
          align="center"
          prop="validEnd"
          v-if="tableColumns.find((col) => col.prop === 'validEnd').visible"
        />

        <!-- 纸质证书发放时间 -->
        <el-table-column
          label="纸质证书发放时间"
          align="center"
          prop="paperIssueTime"
          v-if="
            tableColumns.find((col) => col.prop === 'paperIssueTime').visible
          "
        />

        <!-- 纸质证书领取方式 -->
        <el-table-column
          label="纸质证书领取方式"
          align="center"
          prop="receiveMethod"
          v-if="
            tableColumns.find((col) => col.prop === 'receiveMethod').visible
          "
        >
          <template slot-scope="scope">
            {{
              dict.label.receive_method[scope.row.receiveMethod] ||
              scope.row.receiveMethod
            }}
          </template>
        </el-table-column>

        <!-- 快递单号 -->
        <el-table-column
          label="快递单号"
          align="center"
          prop="trackingNo"
          v-if="tableColumns.find((col) => col.prop === 'trackingNo').visible"
        />

        <!-- 备注 -->
        <el-table-column
          label="备注"
          align="center"
          prop="remark"
          v-if="tableColumns.find((col) => col.prop === 'remark').visible"
        />

        <!-- 操作 -->
        <el-table-column
          label="操作"
          width="280px"
          align="center"
          class-name="small-padding fixed-width"
          v-if="tableColumns.find((col) => col.prop === 'operation').visible"
        >
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              @click="handleRemarkRow(scope.row)"
              v-hasPermi="['certificate:template:remark']"
              >备注</el-button
            >
            <el-button
              size="mini"
              type="text"
              @click="notifyStudent(scope.row)"
              v-hasPermi="['certificate:template:notify']"
              >学员通知</el-button
            >
            <el-button
              size="mini"
              type="text"
              @click="downloadElectronicCertificate"
              v-hasPermi="['certificate:template:download']"
              >下载证书</el-button
            >
            <!-- <el-button
              size="mini"
              type="text"
              @click="printCertificate"
              v-hasPermi="['certificate:template:print']"
              >打印证书</el-button
            > -->
            <el-button
              size="mini"
              type="text"
              @click="copyOrder(scope.row)"
              v-hasPermi="['certificate:template:copy-order']"
              >复制单号</el-button
            >
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-show="total > 0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />

      <!-- 添加或修改题组管理对话框 -->
      <el-dialog
        :title="title"
        :visible.sync="open"
        width="800px"
        custom-class="dialog-custom"
        append-to-body
      >
        <el-form ref="form" :model="form" :rules="rules" label-width="100px">
          <!-- 第一行：题组名称 和 题组题型 -->
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="题组名称" prop="groupName">
                <el-input
                  v-model="form.groupName"
                  placeholder="请输入题组名称"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="题组题型" prop="groupType">
                <el-select
                  v-model="form.groupType"
                  placeholder="请选择题组题型"
                >
                  <el-option
                    v-for="dict in dict.type.question_type"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value"
                  />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>

          <!-- 第二行：项目类别 -->
          <el-form-item label="项目类别" prop="trainingProjectId">
            <el-cascader
              v-model="form.trainingProjectId"
              :options="projectOptions"
              :props="{
                checkStrictly: true,
                emitPath: false, //只传入子节点的id
                value: 'id',
                label: 'label',
                children: 'children',
              }"
              placeholder="请选择项目类别"
              clearable
            />
          </el-form-item>
        </el-form>

        <div slot="footer" class="dialog-footer">
          <el-button @click="cancel">取消</el-button>
          <el-button type="primary" @click="submitForm">提交</el-button>
        </div>
      </el-dialog>

      <!-- 备注 -->
      <RemarkDialogVue
        :visible.sync="remarkDialogVisible"
        :record-id="currentRecordId"
        :remark-history="remarkList"
        :remark-type="'10'"
        @success="refreshRemarkList"
      />
      <!-- 新增个人复审资料 -->
      <add-personal-review
        ref="addPersonalReview"
        :dict-data="dictData"
      ></add-personal-review>
      <!-- 生成电子证书 -->
      <GenerateElectronicCertificateDialogVue
        :visible.sync="generateDialogVisible"
        :certificate-data="selectedCertificates"
        :template-list="templateList"
        @submit="handleGenerateSubmit"
      />
      <!-- 撤销电子证书 -->
      <RevokeElectronicCertificateDialog
        :visible.sync="revokeElectronicVisible"
        :certificate-data="selectedCertificates"
        :template-list="templateList"
        @submit="handleRevokeSubmit"
      />
      <!-- 查看电子证书 -->
      <ViewCertificateDialogVue
        :visible.sync="viewCertificateTemplateDialog"
        :template-data="viewCertificateTemplateData"
      />
      <!-- 快递发放证书 -->
      <FastIssuePaperCertificateDialog
        :visible.sync="fastIssueVisible"
        :certificate-data="FastIssueData"
        @submit="handleFastIssueSubmit"
      />
      <!-- 现场领取证书 -->
      <OnSitePickupDialog
        :visible.sync="onSitePickupVisible"
        :certificate-list="selectedCertificatesForPickup"
        @confirm="handleConfirmPickup"
      />
      <!-- 发起退费 -->
      <InitiateRefundDialog
        :visible.sync="showRefundDialogInitiate"
        :apply-info="refundFormData"
        :dict="dictCache"
        @submit="handleRefundSubmitInitiate"
        @close="handleInitiateRefundClose"
      ></InitiateRefundDialog>
      <!-- 取消退费 -->
      <CancelRefundDialog
        :visible.sync="showRefundDialogCancel"
        :apply-info="refundApplyInfoCancel"
        :dict="dictCache"
        @submit="handleRefundSubmitCancel"
      ></CancelRefundDialog>


      <file-upload-modal
      :visible="showUploadModal"
      :students="students"
      :businessId="registrationIdsUpload"
      :defaultMode="defaultMode"
      @update:visible="val => showUploadModal = val"
      @confirm="handleUploadConfirm"
      @close="handleModalClose"
    />


    <!-- 2. 档案上传确认组件 -->
    <FileUploadConfirmation
      :visible.sync="showFileConfirmation"
      :userData="studentInitialData"
      :registrationId="registrationId"
      dialog-title="员工档案上传确认"
      dialog-width="85%"
      @single-confirm="handleFileSubmit"
      @confirm="handleFileSubmit"
      @midway-confirm="handleMidwaySave"
      @close="closeAllModals"
    />


    <!-- 3. 操作结果提示 -->
    <el-dialog
      :visible.sync="showResultDialog"
      :title="resultSuccess ? '操作成功' : '操作失败'"
      width="400px"
      :close-on-click-modal="false"
    >
      <div class="result-content">
        <i class="el-icon-check-circle success-icon" v-if="resultSuccess"></i>
        <i class="el-icon-error-circle error-icon" v-else></i>
        <p>{{ resultMessage }}</p>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="showResultDialog = false">确定</el-button>
      </div>
    </el-dialog>

    <!-- 学员通知弹窗 -->
      <student-notice-dialog
        :visible.sync="noticeDialogVisible"
        :class-id="currentClassId"
        @notice-sent="handleNoticeSent"
      />
    </el-col>
  </div>
</template>

<script>
import {
  listCertificateReissue,
  getCertificateReissue,
  delCertificateReissue,
  addCertificateReissue,
  updateCertificateReissue,
} from "@/api/certificate/changeCertificate";
import {
  listCertificateIssue,
  getCertificateIssue,
  delCertificateIssue,
  addCertificateIssue,
  updateCertificateIssue,
  getElectronicInfo,
  expressPaperCertificate,
  getCertificateIssueList,
  scenePaperCertificate,
  generateElectronic,
  cancelElectronic,
} from "@/api/certificate/issue";
import { listRemarksByParams } from "@/api/training/remarks";
import { getRegistration } from "@/api/training/registration";
import { listCertificateTemplate } from "@/api/certificate/certificateTemplate";
// import {
//   listCertificateIssue,
//   getCertificateIssue,
//   delCertificateIssue,
//   addCertificateIssue,
//   updateCertificateIssue,
//   getElectronicInfo,
//   expressPaperCertificate,
//   getCertificateIssueList,
//   scenePaperCertificate,
// } from "@/api/certificate/issue";
import { projectTreeSelect } from "@/api/training/projects";
import { getDicts } from "@/api/system/dict/data";
import { changePay, updateRecord, getRefundInfo } from "@/api/payment/payment";
import ColumnConfigDialogVue from "../../../components/ColumnConfig/ColumnConfigDialog.vue";
// 备注
import RemarkDialogVue from "../../../components/Certificate/template/RemarkDialog.vue";
// 新增个人复审资料
import AddPersonalReview from "@/components/Certificate/reexamination/AddPersonalReview.vue";

// 生成电子证书
import GenerateElectronicCertificateDialogVue from "../../../components/Certificate/issue/GenerateElectronicCertificateDialog.vue";
// 快递发放证书
import FastIssuePaperCertificateDialog from "../../../components/Certificate/issue/FastIssuePaperCertificateDialog.vue";
// 现场领取证书
import OnSitePickupDialog from "../../../components/Certificate/issue/OnSitePickupDialog.vue";
// 发起退费
import InitiateRefundDialog from "@/components/Payment/InitiateRefundDialog.vue";
// 取消退费
import CancelRefundDialog from "@/components/Payment/CancelRefundDialog.vue";
// 撤销电子证书
import RevokeElectronicCertificateDialog from "../../../components/Certificate/issue/RevokeElectronicCertificateDialog.vue";
// 查看电子证书
import ViewCertificateDialogVue from "../../../components/Certificate/issue/ViewCertificateDialog.vue";
// 导入工具类
import CertificateDownloader from "../../../components/Certificate/issue/certificateDownloader";

import FileUploadModal from "@/components/FileUpload/FileUploadModal.vue";
import FileUploadConfirmation from '@/components/FileUpload/FileUploadConfirmation.vue';
import {handleRecordsSubmit,selectRecordsByRegistrationIds} from "@/api/training/records";
import studentNoticeDialog from "@/components/class/studentNoticeDialog.vue";


export default {
  name: "CertificateReissue",
  dicts: [
    "certificate_type",
    "digital_status",
    "paper_status",
    "registration_method",
    "payment_status",
    "record_status",
    "invoice_status",
    "receive_method",
    "payment_method",
    "training_type",
    "expire_reminder_days",
  ],
  components: {
    ColumnConfigDialogVue,
    RemarkDialogVue,
    AddPersonalReview,
    GenerateElectronicCertificateDialogVue,
    FastIssuePaperCertificateDialog,
    OnSitePickupDialog,
    InitiateRefundDialog,
    CancelRefundDialog,
    RevokeElectronicCertificateDialog,
    ViewCertificateDialogVue,
    FileUploadModal,
    FileUploadConfirmation,
    studentNoticeDialog
  },
  data() {
    return {
      currentClassId: '',
      noticeDialogVisible: false,

      registrationId:"",
      registrationIds:[],
      //档案数量
      recordDto:null,
      fileLimit:6,
      // 模态框控制
      showUploadModal: false,
      showFileConfirmation: false,
      showResultDialog: false,


      // 结果信息
      resultSuccess: false,
      resultMessage: '',
      submitResult: null,


      // 上传配置
      defaultMode: "0", // 覆盖模式 (cover 0 / append 1)
      registrationIdsUpload: "", // 报名id

      // 学员列表数据
      students: null,


      // 学员初始档案数据（模拟从后端获取）
      studentInitialData: [{
              id:0,
              name:"",
              registrationId:"",
              urls: [],
              remark:"",
              fileTypes:[]
              }],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 换证管理表格数据
      certificateIssueList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        certificateType: null,
        digitalStatus: null,
        paperStatus: null,
        certificateNo: null,
        digitalIssueTime: null,
        originalValidityStart: null,
        originalValidityEnd: null,
        originalCertificateNo: null,
        certificateReissueFee: null,
        paymentId: null,
        invoiceId: null,
        validityStart: null,
        validityEnd: null,
        paperIssueTime: null,
        receiveMethod: null,
        immediatePublish: null,
        expireReminderDays: null,
        revokeReason: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        trainingProjectId: [
          { required: true, message: "项目类别不能为空", trigger: "change" },
        ],
      },
      //新增数据定义
      //树形结构数据
      // 所有部门树选项
      projectName: "",
      projectOptions: [],
      defaultProps: {
        children: "children",
        label: "label",
      },
      // 缓存字典数据
      dictCache: {
        certificate_type: {},
        digital_status: {},
        paper_status: {},
        registration_method: {},
        payment_status: {},
        invoice_status: {},
        record_status: {},
        receive_method: {},
        payment_method: {},
        training_type: {},
      },
      // 添加字典数据存储
      dictData: {
        unitNatureOptions: [],
        documentTypeOptions: [],
        nationOptions: [],
        educationOptions: [],
        administrativeAreaOptions: [],
        userTypeOptions: [],
      },
      // 列显隐
      tableColumns: [
        { prop: "certificateType", label: "证书类型", visible: true },
        { prop: "digitalStatus", label: "电子证书状态", visible: true },
        { prop: "paperStatus", label: "纸质证书状态", visible: true },
        { prop: "certificateNo", label: "证书编号", visible: true },
        { prop: "studentName", label: "姓名", visible: true },
        { prop: "idNumber", label: "证件编号", visible: true },
        { prop: "sex", label: "性别", visible: true },
        { prop: "phonenumber", label: "电话", visible: true },
        { prop: "unitName", label: "单位名称", visible: true },
        // { prop: "trainingProjectName", label: "培训项目", visible: true },
        { prop: "projectName", label: "培训项目", visible: true },
        { prop: "registrationMethod", label: "报名来源", visible: true },
        { prop: "contact", label: "联系人", visible: true },
        { prop: "unitPhonenumber", label: "联系人电话", visible: true },
        {
          prop: "originalValidityStart",
          label: "原证书有效期起",
          visible: true,
        },
        { prop: "originalValidityEnd", label: "原证书有效期止", visible: true },
        { prop: "originalCertificateNo", label: "原证书编号", visible: true },
        { prop: "certificateReissueFee", label: "费用", visible: true },
        { prop: "paymentState", label: "缴费状态", visible: true },
        { prop: "invoiceStatus", label: "发票状态", visible: true },
        { prop: "recordStatus", label: "档案状态", visible: true },
        { prop: "recordMissing", label: "档案缺失情况", visible: true },
        { prop: "submissionStatus", label: "提交状态", visible: true },
        { prop: "issueTime", label: "证书发放时间", visible: true },
        { prop: "validStart", label: "证书有效期起", visible: true },
        { prop: "validEnd", label: "证书有效期止", visible: true },
        { prop: "paperIssueTime", label: "纸质证书发放时间", visible: true },
        { prop: "receiveMethod", label: "纸质证书领取方式", visible: true },
        { prop: "trackingNo", label: "快递单号", visible: true },
        { prop: "enrollmentTime", label: "报名时间", visible: true },
        { prop: "remark", label: "备注", visible: true },
        { prop: "operation", label: "操作", visible: true },
      ],
      //备注
      remarkDialogVisible: false,
      currentRecordId: "",
      remarkList: [], // 存储备注历史
      // 生成电子证书
      generateDialogVisible: false,
      selectedCertificates: [],
      //快递发放证书
      fastIssueVisible: false,
      FastIssueData: [],
      // 现场领取证书
      onSitePickupVisible: false,
      tempIssueData: [], //多选数据
      selectedCertificatesForPickup: [], // 存储选中的证书数据
      //缴费ids
      tempPaymentRecordIds: [],
      // 退费发起
      showRefundDialogInitiate: false,
      refundFormData: {},
      // 退费取消
      showRefundDialogCancel: false,
      refundApplyInfoCancel: {},
      //模板下拉列表
      templateList: [],
      //撤销电子证书
      revokeElectronicVisible: false,
      //查看电子证书
      viewCertificateTemplateDialog: false,
      viewCertificateTemplateData: [],
    };
  },
  created() {
    this.getList();
    this.getProjectTree();
    this.$nextTick(async () => {
      await this.loadDicts();
    });
    this.loadAllDicts();
  },
  filters: {
    formatDate(value) {
      if (value) {
        return moment(value).format("YYYY-MM-DD HH:mm:ss");
      }
      return "";
    },
  },
  methods: {
    async loadDicts() {
      this.dictCache.certificate_type = this.dict.label.certificate_type;
      this.dictCache.digital_status = this.dict.label.digital_status;
      this.dictCache.paper_status = this.dict.label.paper_status;
      this.dictCache.registration_method = this.dict.label.registration_method;
      this.dictCache.record_status = this.dict.label.record_status;
      this.dictCache.payment_status = this.dict.label.payment_status;
      this.dictCache.invoice_status = this.dict.label.invoice_status;
      this.dictCache.receive_method = this.dict.label.receive_method;
      this.dictCache.payment_method = this.dict.label.payment_method;
      this.dictCache.training_type = this.dict.label.training_type;
    },
    // 统一加载所有字典数据
    loadAllDicts() {
      const dictPromises = [
        getDicts("unit_nature"),
        getDicts("pxzx_zjlx"),
        getDicts("pub_mz"),
        getDicts("pxzx_xl"),
        getDicts("administrative_area"),
        getDicts("rylx"),
      ];

      Promise.all(dictPromises)
        .then((responses) => {
          this.dictData.unitNatureOptions = responses[0].data;
          this.dictData.documentTypeOptions = responses[1].data;
          this.dictData.nationOptions = responses[2].data;
          this.dictData.educationOptions = responses[3].data;
          this.dictData.administrativeAreaOptions = responses[4].data;
          this.dictData.userTypeOptions = responses[5].data;
        })
        .catch((error) => {
          console.error("字典数据加载失败:", error);
        });
    },
    /** 查询换证管理列表 */
    getList() {
      this.loading = true;
      getCertificateIssueList(this.queryParams).then((response) => {
        this.certificateIssueList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        certificateReissueId: null,
        templateId: null,
        studentId: null,
        projectId: null,
        registrationId: null,
        certificateType: null,
        digitalStatus: null,
        paperStatus: null,
        certificateNo: null,
        digitalIssueTime: null,
        originalValidityStart: null,
        originalValidityEnd: null,
        originalCertificateNo: null,
        certificateReissueFee: null,
        paymentId: null,
        invoiceId: null,
        validityStart: null,
        validityEnd: null,
        paperIssueTime: null,
        receiveMethod: null,
        paperApplyTime: null,
        trackingNo: null,
        immediatePublish: null,
        expireReminderDays: null,
        revokeReason: null,
        createdBy: null,
        updatedBy: null,
        createdTime: null,
        updatedTime: null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      // 将时间范围拆分为 start 和 end
      if (this.queryParams.issueTimeRange) {
        this.queryParams.createStartTime = this.queryParams.issueTimeRange[0];
        this.queryParams.createEndTime = this.queryParams.issueTimeRange[1];
      }
      if (this.queryParams.validStart) {
        this.queryParams.createStartTime = this.queryParams.validStart[0];
        this.queryParams.createEndTime = this.queryParams.validStart[1];
      }
      if (this.queryParams.validEnd) {
        this.queryParams.createStartTime = this.queryParams.validEnd[0];
        this.queryParams.createEndTime = this.queryParams.validEnd[1];
      }
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.queryParams = {
        pageNum: 1,
        pageSize: 10,
      };
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.recordDto=selection
      this.registrationIds = selection.map((item) => item.registrationId);

      this.ids = selection.map((item) => item.certificateIssueId);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
      // 将选中的数据赋值给 FastIssueData
      this.tempIssueData = selection;
      this.tempPaymentRecordIds = selection.map((item) => item.paymentId);
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加换证管理";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const certificateReissueId = row.certificateReissueId || this.ids;
      getCertificateReissue(certificateReissueId).then((response) => {
        this.form = response.data;
        this.open = true;
        this.title = "修改换证管理";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.certificateReissueId != null) {
            updateCertificateReissue(this.form).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addCertificateReissue(this.form).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const certificateReissueIds = row.certificateReissueId || this.ids;
      this.$modal
        .confirm(
          '是否确认删除换证管理编号为"' + certificateReissueIds + '"的数据项？'
        )
        .then(function () {
          return delCertificateReissue(certificateReissueIds);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "training/certificateReissue/export",
        {
          ...this.queryParams,
        },
        `certificateReissue_${new Date().getTime()}.xlsx`
      );
    },

    //新增方法
    //树形结构
    filterTree() {
      this.$refs.tree.filter(this.projectName);
    },
    // 获取树形数据
    getProjectTree(val) {
      var params = { projectName: val };
      params.projectId = this.queryParams.projectId;
      projectTreeSelect(params).then((response) => {
        this.projectOptions = response.data;
      });
    },
    filterNode(value, data) {
      if (!value) return true;
      return data.label.indexOf(value) !== -1;
    },
    handleNodeClick(data) {
      this.queryParams.trainingProjectId = data.id;
      this.queryParams.pageNum = 1;
      this.getList();
    },
    flattenTree(tree) {
      let result = [];
      tree.forEach((node) => {
        result.push({ id: node.id, label: node.label });
        if (node.children && node.children.length > 0) {
          result = result.concat(this.flattenTree(node.children));
        }
      });
      return result;
    },
    // 切换搜索显示
    toggleSearch() {
      this.showSearch = !this.showSearch;
    },
    // 刷新表格数据
    refreshTable() {
      this.getList();
    },
    // 切换排序列显示
    toggleSort() {
      // 根据实际需求实现排序列的显示/隐藏逻辑
      this.$message.info("排序列功能待实现");
    },

    //证书

    //报名信息
    // 查看详情
    handleView() {
      const selectedRow = this.certificateIssueList.find(
        (item) => item.certificateIssueId === this.ids[0]
      );
      getRegistration(selectedRow.registrationId).then((response) => {
        this.$refs.addPersonalReview.open("view", response.data);
      });
    },
    handleEdit() {
      // 检查是否选中了数据
      if (this.ids.length !== 1) {
        this.$message.warning("请选择一条记录进行修改");
        return;
      }

      // 从列表中找到选中的记录
      const selectedRow = this.certificateIssueList.find(
        (item) => item.certificateIssueId === this.ids[0]
      );

      if (selectedRow) {
        console.log("selectedRow:", selectedRow);
        getRegistration(selectedRow.registrationId).then((response) => {
          this.$refs.addPersonalReview.open("edit", response.data);
        });
      }
    },
    // 删除证书模板
    handleDeleteTemplate() {
      this.$message.info("删除证书模板功能待实现");
    },
    // 备注
    handleRemark() {
      if (this.ids.length !== 1) {
        this.$message.warning("请选择一条记录进行备注");
        return;
      }

      const row = this.certificateIssueList.find(
        (item) => item.certificateIssueId === this.ids[0]
      );
      if (!row) return;

      this.currentRecordId = row.certificateIssueId;

      var params = { foreignId: row.certificateIssueId, remarkType: "10" };

      listRemarksByParams(params).then((res) => {
        this.remarkList = res.rows;
        this.remarkDialogVisible = true;
      });
    },
    // 查看证书
    handleViewCertificate(row) {
      this.$message.info(`查看证书：${row.certificateName}`);
    },
    // 复制
    handleCopy(row) {
      this.$message.info(`复制证书：${row.certificateName}`);
    },
    // 备注行
    handleRemarkRow(row) {
      var params = { foreignId: row.certificateReissueId, remarkType: "10" };
      listRemarksByParams(params).then((res) => {
        this.remarkList = res.rows;
        this.remarkDialogVisible = true;
      });
    },

    // 刷新备注列表
    refreshRemarkList(remark) {
      this.getRemarkHistory(this.currentRecordId);
    },

    // 通知学员
    notifyStudent(row) {
      // if (this.ids.length === 0) {
      //   this.$message.warning("请先选择学员");
      //   return;
      // }
      let targetRow =null;
      // 优先获取行数据，无则取选中数据
      if(row.studentId !==undefined){
        targetRow =row
      }else{
        targetRow = this.recordDto[0];
        if (!targetRow ) return this.$message.warning('请选择一个学员');
      }
      this.currentClassId=targetRow.trainingClassId+""
      this.noticeDialogVisible =true

      // // 示例：调用 API 发送通知
      // this.$api.certificate
      //   .notifyStudents({ ids: this.ids })
      //   .then(() => {
      //     this.$modal.msgSuccess("通知发送成功");
      //   })
      //   .catch((err) => {
      //     this.$message.error("通知发送失败：" + err.message);
      //   });
    },
    // 生成电子证书
    generateElectronicCertificate() {
      if (this.ids.length === 0) {
        this.$message.warning("请先选择学员");
        return;
      }

      // 获取选中的证书数据
      this.selectedCertificates = this.certificateIssueList.filter((item) =>
        this.ids.includes(item.certificateIssueId)
      );

      //模板列表数据
      listCertificateTemplate().then((res) => {
        console.log("模板列表数据：", res);
        this.templateList = res.rows;
        // 确保数据加载完成后再显示对话框
        this.$nextTick(() => {
          this.generateDialogVisible = true;
        });
      });
    },

    // 撤销电子证书
    revokeElectronicCertificate() {
      if (this.ids.length === 0) {
        this.$message.warning("请先选择学员");
        return;
      }
      // 获取选中的证书数据
      this.selectedCertificates = this.certificateIssueList.filter((item) =>
        this.ids.includes(item.certificateIssueId)
      );

      //模板列表数据
      listCertificateTemplate().then((res) => {
        this.templateList = res.rows;
        // 确保数据加载完成后再显示对话框
        this.$nextTick(() => {
          this.revokeElectronicVisible = true;
        });
      });
    },

    // 查看电子证书
    viewElectronicCertificate() {
      if (this.ids.length !== 1) {
        this.$message.warning("请选择一条记录查看证书");
        return;
      }

      // 获取所有选中的证书数据
      const certificateIssueIds = this.ids[0];

      // 调用接口批量获取电子证书信息
      getElectronicInfo(certificateIssueIds)
        .then((res) => {
          const certificates = res.data || [];

          if (certificates.length === 0) {
            this.$message.warning("未获取到证书信息");
            return;
          }
          this.viewCertificateTemplateData = certificates;

          // 替换原来的打印语句
          console.log("父组件传递的数据", this.viewCertificateTemplateData);

          // 确保数据已经设置后再显示对话框
          this.$nextTick(() => {
            this.viewCertificateTemplateDialog = true;
          });
        })
        .catch((err) => {
          this.$message.error("获取证书失败：" + err.message);
        });
    },

    // 下载电子证书
    async downloadElectronicCertificate() {
      if (this.ids.length === 0) {
        this.$message.warning("请先选择学员");
        return;
      }

      try {
        // 获取证书数据
        const certificateIssueIds = this.ids;
        const res = await getElectronicInfo(certificateIssueIds);
        const certificates = res.data || [];

        // 使用工具类下载证书
        await CertificateDownloader.downloadCertificates(certificates);

        this.$message.success("证书下载成功");
      } catch (error) {
        this.$message.error("下载失败：" + error.message);
      }
    },

    // 发送电子证书
    sendElectronicCertificate() {
      if (this.ids.length === 0) {
        this.$message.warning("请先选择学员");
        return;
      }
      // this.$api.certificate
      //   .sendElectronicCertificates({ ids: this.ids })
      //   .then(() => {
      //     this.$modal.msgSuccess("电子证书已发送");
      //     this.getList();
      //   })
      //   .catch((err) => {
      //     this.$message.error("发送失败：" + err.message);
      //   });
    },
    // 报名复训换证
    handleRenewalApply() {
      this.$refs.addPersonalReview.open("add");
    },
    // 快递发放证书
    fastIssuePaperCertificate() {
      if (this.ids.length === 0) {
        this.$message.warning("请先选择学员");
        return;
      }
      this.FastIssueData = this.tempIssueData.map((item) => ({
        certificateIssueId: item.certificateIssueId,
        certificateNo: item.certificateIssueId,
        studentName: item.studentName,
        idNumber: item.idNumber,
        phonenumber: item.phonenumber,
        trackingNo: item.trackingNo,
      }));

      this.fastIssueVisible = true;
    },
    // 快递发放证书
    handleFastIssueSubmit(data) {
      console.log(data);

      expressPaperCertificate(data)
        .then(() => {
          this.$modal.msgSuccess("证书已安排快递发放");
          this.getList(); // 刷新列表
          this.fastIssueVisible = false; // 关闭对话框
        })
        .catch((err) => {
          this.$message.error("发放失败：" + err.message);
        });
    },

    // 打印证书
    printCertificate() {
      if (this.ids.length !== 1) {
        this.$message.warning("请选择一条记录进行打印");
        return;
      }
      const id = this.ids[0];
      // this.$api.certificate
      //   .getPrintableCertificate(id)
      //   .then((res) => {
      //     // 假设返回的是 PDF 或 HTML 内容，可以使用 window.open 或 iframe 打印
      //     window.open(res.data.url, "_blank");
      //   })
      //   .catch((err) => {
      //     this.$message.error("获取打印内容失败：" + err.message);
      //   });
    },
    // 复制单号
    copyOrder(row) {
      if (!row || !row.trackingNo) {
        this.$message.warning("该记录无快递单号");
        return;
      }
      navigator.clipboard
        .writeText(row.trackingNo)
        .then(() => {
          this.$message.success("快递单号已复制到剪贴板");
        })
        .catch(() => {
          this.$message.error("复制失败");
        });
    },
    // 生成电子证书
    openGenerateDialog() {
      if (this.ids.length === 0) {
        this.$message.warning("请先选择学员");
        return;
      }

      // 获取选中的证书数据
      this.selectedCertificates = this.questionGroupList.filter((item) =>
        this.ids.includes(item.groupId)
      );

      this.generateDialogVisible = true;
    },

    handleGenerateSubmit(data) {
      generateElectronic(data)
        .then(() => {
          this.$modal.msgSuccess("电子证书生成成功");
          this.getList(); // 刷新列表
          this.generateDialogVisible = false; // 关闭对话框
        })
        .catch((err) => {
          this.$message.error("生成失败：" + err.message);
        });
    },
    handleRevokeSubmit(data) {
      console.log("提交的数据：", data);

      cancelElectronic(data)
        .then(() => {
          this.$modal.msgSuccess("撤销电子证书成功");
          this.getList(); // 刷新列表
          this.generateDialogVisible = false; // 关闭对话框
        })
        .catch((err) => {
          this.$message.error("生成失败：" + err.message);
        });
    },
    // 现场领取证书
    onSitePickupCertificate() {
      if (this.ids.length === 0) {
        this.$message.warning("请先选择学员");
        return;
      }

      this.selectedCertificatesForPickup = this.tempIssueData.map((item) => ({
        certificateIssueId: item.certificateIssueId,
        certificateNo: item.certificateIssueId,
        studentName: item.studentName,
        idNumber: item.idNumber,
        phonenumber: item.phonenumber,
        trackingNo: item.trackingNo,
      }));

      this.onSitePickupVisible = true;
    },
    // 显示现场领取弹窗
    showOnSitePickupDialog() {
      if (this.ids.length === 0) {
        this.$message.warning("请先选择学员");
        return;
      }

      // 获取选中行的数据
      this.selectedCertificatesForPickup = this.certificateIssueList.filter(
        (item) => this.ids.includes(item.groupId)
      );

      this.onSitePickupVisible = true;
    },

    // 确认现场领取
    handleConfirmPickup() {
      const ids = this.selectedCertificatesForPickup.map(
        (item) => item.groupId
      );

      // this.$api.certificate
      //   .onSitePickupCertificates({ ids })
      //   .then(() => {
      //     this.$modal.msgSuccess("证书已标记为现场领取");
      //     this.getList(); // 刷新列表
      //     this.onSitePickupVisible = false;
      //   })
      //   .catch((err) => {
      //     this.$message.error("标记失败：" + err.message);
      //   });
    },
    // 缴费方式
    handlePaymentMethodChange(val) {
      const params = {
        paymentRecordIds: this.tempPaymentRecordIds,
        paymentMethod: val.toString(),
      };
      changePay(params)
        .then((response) => {
          this.$message.success("缴费方式更新成功");
          this.getList(); // 刷新列表
        })
        .catch((error) => {
          this.$message.error("缴费方式更新失败：" + error.message);
        });
    },
    handleStartRefund() {
      if (!this.ids || this.ids.length === 0) {
        this.$message.warning("请选择一条记录进行退费");
        return;
      }
      // 实现发起退费逻辑
      const selectedRow = this.certificateIssueList.find(
        (item) => item.certificateIssueId === this.ids[0]
      );
      if (selectedRow) {
        getRefundInfo(selectedRow.paymentId).then((res) => {
          this.refundFormData = res.data;
        });
      } else {
        this.$message.warning("请选择一条记录进行退费");
        return;
      }

      this.showRefundDialogInitiate = true;
    },
    //发起退款
    handleRefundSubmitInitiate(submitData) {
      // 处理提交后关闭对话框
      const selectedRow = this.certificateIssueList.find(
        (item) => item.certificateIssueId === this.ids[0]
      );
      var params = {
        paymentRecordId: selectedRow.paymentId,
        refundAmount: submitData.auditForm.refundAmount,
        refundReason: submitData.auditForm.refundReason,
        paymentState: "6",
      };

      if (selectedRow) {
        updateRecord(params).then((res) => {
          this.showRefundDialogInitiate = false;
          this.getList(); // 刷新列表
        });
      } else {
        this.$message.warning("请选择一条记录进行退费");
        return;
      }
    },
    handleInitiateRefundClose() {
      this.showRefundDialogInitiate = false;
    },
    handleCancelRefund() {
      // 实现取消退费逻辑
      const selectedRow = this.certificateIssueList.find(
        (item) => item.certificateIssueId === this.ids[0]
      );

      getRefundInfo(selectedRow.paymentId).then((res) => {
        this.refundApplyInfoCancel = res.data;

        console.log("回显信息:", this.refundApplyInfoCancel);
      });

      this.showRefundDialogCancel = true;
    },
    // 取消退费申请---提交
    handleRefundSubmitCancel() {
      // 处理提交后关闭对话框
      const selectedRow = this.certificateIssueList.find(
        (item) => item.certificateIssueId === this.ids[0]
      );
      var params = {
        paymentRecordId: selectedRow.paymentId,
        paymentState: "1",
      };
      if (selectedRow) {
        updateRecord(params).then(() => {
          this.showRefundDialogCancel = false;
          this.getList(); // 刷新列表
        });
      } else {
        this.$message.warning("请选择一条记录进行退费");
        return;
      }
    },


    /**
     * 处理FileUploadModal的确认事件
     * 上传完成后自动跳转到确认页面，并更新学员档案数据
     */
    getUrlsBySecondDir(query, fileList) {
    // 初始化结果数组
    const resultUrls = [];

    // 遍历文件列表
    fileList.forEach(file => {
        // 分割relativePath为目录数组（按"/"分割）
        const pathSegments = file.relativePath.split('/');
        // 校验路径格式（至少包含三级：一级/二级/文件名）
        if (pathSegments.length >= 3) {
            // 二级目录为数组的第1个索引（索引从0开始）
            const secondDir = pathSegments[1];
            // 精确匹配二级目录与查询字符串
            if (secondDir === query) {

                      // 匹配成功则添加url到结果数组
                      resultUrls.push(file.url);
                  }
              }
          })
          return resultUrls;
      },
    handleUploadConfirm(result) {
      console.log("文件上传完成，开始处理数据：", result);
      if(result.uploadMode === "1"){
          const targetStudents=result.targetStudents
          this.studentInitialData=targetStudents.map(item =>{
            let name =item.name
            let resultUrls =[]
            for(let i=0;i<this.students.length;i++){
              if(name === this.students[i].name){
                resultUrls = this.students[i].urls
              }
            }
            const Urls = this.getUrlsBySecondDir(name, result.fileDetails);
            console.log(Urls)
            const fileLimit = this.fileLimit;
            let finalUrls =resultUrls.concat(Urls);
            let emptyUrlCount = 0;
            if( fileLimit - Urls.length >=0){
              emptyUrlCount = fileLimit - Urls.length;
              for (let i = 0; i < emptyUrlCount; i++) {
                finalUrls.push("");
              }
            }
            let remark="";
            let fileTypes=[];
            for(let i=0;i<this.students.length;i++){
              if(item.id === this.students[i].id){
                remark =this.students[i].remark
                fileTypes= this.students[i].fileTypes;
              }
            }

            if( fileLimit - fileTypes.length >=0){
              const num = fileLimit - fileTypes.length;
              for (let i = 0; i < num; i++) {
                fileTypes.push("");
              }
            }

            return {
              id:item.id,
              name:name,
              registrationId:item.id,
              urls: finalUrls,
              remark:remark,
              fileTypes:fileTypes
              }
          })
          console.log(this.studentInitialData)
      }else{
        const targetStudents=result.targetStudents
          this.studentInitialData=targetStudents.map(item =>{
            let name =item.name
            let resultUrls =[]
            const Urls = this.getUrlsBySecondDir(name, result.fileDetails);
            const fileLimit = this.fileLimit;
            let finalUrls =resultUrls.concat(Urls);
            let emptyUrlCount = 0;
            if( fileLimit - Urls.length >=0){
              emptyUrlCount = fileLimit - Urls.length;
              for (let i = 0; i < emptyUrlCount; i++) {
                finalUrls.push("");
              }
            }
            let remark="";
            let fileTypes=[];

            if( fileLimit - fileTypes.length >=0){
              const num = fileLimit - fileTypes.length;
              for (let i = 0; i < num; i++) {
                fileTypes.push("");
              }
            }

            return {
              id:item.id,
              name:name,
              registrationId:item.id,
              urls: finalUrls,
              remark:remark,
              fileTypes:fileTypes
              }
          })
          console.log(this.studentInitialData)
      }

      // 关闭上传模态框
      this.showUploadModal = false;

      // 核心：更新学员档案数据（按姓名分组URL）
      this.updateStudentDataAfterUpload(result);

      // 显示确认页面
      this.showFileConfirmation = true;

      // 滚动到页面顶部
      window.scrollTo(0, 0);
    },


    /**
     * 处理FileUploadConfirmation的提交事件
     */
    handleFileSubmit(submitData) {
      console.log('档案信息提交，数据结构：', submitData);

      // 保存提交结果（调试用）
      this.submitResult = submitData;

      // 模拟API请求（实际项目替换为真实接口）
      handleRecordsSubmit(submitData).then((response) => {
        // 显示成功提示
        this.resultSuccess = true;
        this.resultMessage = "档案信息已成功保存至服务器";
        this.showResultDialog = true;

        // 关闭确认页面
        this.showFileConfirmation = false;
      });
    },
    handleMidwaySave(submitData) {
      console.log('中途保存数据（当前及之前用户）:', submitData);
      // 保存提交结果（调试用）
      this.submitResult = submitData;

      // 模拟API请求（实际项目替换为真实接口）
      handleRecordsSubmit(submitData).then((response) => {
        console.log(response.rows);
        // 显示成功提示
        this.resultSuccess = true;
        this.resultMessage = "档案信息已成功保存至服务器";
        this.showResultDialog = true;

        // 关闭确认页面
        this.showFileConfirmation = false;
      });
    },


    /**
     * 关闭所有模态框/组件
     */
    closeAllModals() {
      this.showUploadModal = false;
      this.showFileConfirmation = false;
    },


    /**
     * 处理上传模态框关闭事件
     */
    handleModalClose() {
      // console.log("上传模态框已手动关闭");
      this.showUploadModal = false;
    },


    /**
     * 核心方法：上传后更新学员档案数据（按姓名分组URL）
     * @param {Object} uploadResult - 上传结果数据（含fileDetails和relativePath）
     */
    updateStudentDataAfterUpload(uploadResult) {
      // 1. 校验上传结果有效性
      if (!uploadResult || !uploadResult.fileDetails || uploadResult.fileDetails.length === 0) {
        this.$message.warning("未获取到有效上传文件，学员档案未更新");
        return;
      }

      try {
        // 2. 按学员姓名分组URL（从relativePath提取姓名，新格式：test/学员姓名/文件名）
        const studentUrlMap = this.groupUrlsByStudentName(uploadResult.fileDetails);
        if (Object.keys(studentUrlMap).length === 0) {
          this.$message.warning("未从文件路径中提取到有效学员姓名，无法更新档案");
          return;
        }

        // 3. 根据分组结果更新对应学员的URLs
        this.updateStudentUrlsByGroup(studentUrlMap,uploadResult.uploadMode);

        // 4. 提示更新结果
        const updatedStudentCount = Object.keys(studentUrlMap).length;
        this.$message.success(`已成功更新${updatedStudentCount}名学员的档案，共新增${uploadResult.fileDetails.length}个文件`);

      } catch (error) {
        // console.error("更新学员档案时发生错误：", error);
        this.$message.error(`档案更新失败：${error.message || '未知错误'}`);
      }
    },


    /**
 * 辅助方法1：从fileDetails中按学员姓名分组URL（核心：解析relativePath）
 * @param {Array} fileDetails - 上传文件详情数组（含relativePath和url）
 * @returns {Object} 学员姓名→URL数组的映射（格式：{ "张三": [url1, url2] }）
 * @description 适配三层路径格式：任意前缀/学员姓名/文件名.后缀
 */
  groupUrlsByStudentName(fileDetails) {
    const studentUrlMap = {};

    fileDetails.forEach((file, index) => {
      // 1. 基础校验：文件详情必须包含relativePath和url
      if (!file.relativePath || !file.url) {
        // console.warn(`第${index + 1}个文件信息不完整（缺少路径或URL），跳过处理`);
        return;
      }

      // 2. 解析路径：按"/"分割，过滤空片段（处理前后斜杠导致的空值）
      const pathSegments = file.relativePath.split("/")
        .filter(segment => segment.trim() !== "");

      // 3. 格式校验：必须满足三层结构 "任意前缀/学员姓名/文件名" → 至少3个有效片段
      if (pathSegments.length < 3) {
        // console.warn(`第${index + 1}个文件路径格式错误（应为"任意前缀/学员姓名/文件名"）：${file.relativePath}，跳过处理`);
        return;
      }

      // 4. 提取学员姓名：第2个有效片段（索引1，三层结构中固定为学员姓名位置）
      const studentName = pathSegments[1].trim()
        .replace(/[^\u4e00-\u9fa5a-zA-Z0-9]/g, ""); // 只保留中文、字母、数字

      // 5. 姓名有效性校验
      if (!studentName) {
        // console.warn(`第${index + 1}个文件路径中未提取到有效学员姓名：${file.relativePath}，跳过处理`);
        return;
      }

      // 6. 分组URL（去重，避免重复添加同一文件）
      if (!studentUrlMap[studentName]) {
        studentUrlMap[studentName] = [];
      }
      if (!studentUrlMap[studentName].includes(file.url)) {
        studentUrlMap[studentName].push(file.url);
        // console.log(`文件关联成功：学员「${studentName}」→ 文件名「${file.name}」→ URL「${file.url}」`);
      } else {
        // console.log(`文件已存在：学员「${studentName}」的「${file.name}」无需重复添加`);
      }
    });

    return studentUrlMap;
  },


    /**
     * 辅助方法2：根据姓名分组结果，更新studentInitialData对应学员的URLs
     * @param {Object} studentUrlMap - 学员姓名→URL数组的映射
     */
    updateStudentUrlsByGroup(studentUrlMap,uploadMode) {
      this.studentInitialData.forEach((student, studentIndex) => {
        // 找到当前学员在分组中的新URL列表
        const newUrls = studentUrlMap[student.name] || [];
        if (newUrls.length === 0) return; // 无对应新URL，跳过当前学员

        // 1. 保留学员原有非空URL（避免覆盖已存在的有效档案）
        const existingValidUrls = student.urls.filter(url => url && url.trim() !== "");
        console.log(`学员「${student.name}」原有有效档案数：${existingValidUrls.length}个`);

        // 2. 合并原有URL和新URL（去重处理）
        const mergedUrls = [...new Set([...existingValidUrls, ...newUrls])];
        console.log(`学员「${student.name}」合并后总档案数：${mergedUrls.length}个`);

        // 3. 按规则限制文件数量
        const fileLimit = this.fileLimit; // 所有学员最多6个文件
        const finalUrls = mergedUrls.slice(0, fileLimit); // 超过限制时截取前N个

        // 4. 补充空URL至限制数量（保持界面显示一致，空URL对应"点击上传"提示）
        const emptyUrlCount = fileLimit - finalUrls.length;
        for (let i = 0; i < emptyUrlCount; i++) {
          finalUrls.push("");
        }

        // 5. 响应式更新学员URLs（必须用$set确保Vue检测到数组变化）
        this.$set(student, "urls", finalUrls);
        // console.log(uploadMode)
        // if(uploadMode === "1"){
        //   console.log(student.urls)
        //   const mergedUrls = [...new Set([...student.urls, ...newUrls])];student.urls
        //   console.log(mergedUrls)
        //   this.$set(student, "urls", mergedUrls);
        // }else{
        //   console.log(newUrls)
        //   this.$set(student, "urls", newUrls);
        // }

        // 6. 日志提示最终结果
        const addedCount = mergedUrls.length - existingValidUrls.length;
        // console.log(
        //   `学员「${student.name}」档案更新完成：新增${addedCount}个，当前共${finalUrls.filter(url => url).length}个有效档案（限制${fileLimit}个）`
        // );
      });
    },

    /**
     * 刷新学员数据（从后端获取最新数据，实际项目使用）
     */
    refreshStudentData() {
      this.$message.info('正在从服务器刷新最新档案数据...');

      // 模拟API请求（实际项目替换为真实接口）
      setTimeout(() => {
        // 响应式更新学员初始数据
        // this.studentInitialData = mockNewData;
        this.$message.success('档案数据已刷新，与服务器保持同步');
      }, 1000);
    },
    async handleExportTest1() {
      console.log(this.recordDto)
      this.registrationIdsUpload = this.registrationIds.join(',');
      if(this.ids.length !=0 ){
        this.registrationId =this.recordDto[0].registrationId
      }
      const response = await selectRecordsByRegistrationIds(this.registrationIdsUpload);
      this.students=response.map(item =>{
          const recordsList=item.recordsList
          let fileTypes=[]
          let urls=[]
          for(let i=0;i<recordsList.length;i++){
            fileTypes.push(recordsList[i].recordType)
            urls.push(recordsList[i].url)
          }
          return {
            id:item.registrationId,
            name:item.studentName,
            requirements: ["身份证", "报名表"],
            remark:item.remark,
            fileTypes:fileTypes,
            urls:urls
          }
        })
      this.showUploadModal=true
    },
    async handleExportTest2() {
      this.registrationIdsUpload = this.registrationIds.join(',');
      if(this.ids.length !=0 ){
        this.registrationId =this.recordDto[0].registrationId
      }
      const response=await selectRecordsByRegistrationIds(this.registrationIdsUpload)
      this.students=response.map(item =>{
          const recordsList=item.recordsList
          let fileTypes=[]
          let urls=[]
          for(let i=0;i<recordsList.length;i++){
            fileTypes.push(recordsList[i].recordType)
            urls.push(recordsList[i].url)
          }

          //补充
          let resultUrls =[]
          let resultFileTypes =[]
          const fileLimit = this.fileLimit;
            let finalUrls =resultUrls.concat(urls);
            let emptyUrlCount = 0;
            if( fileLimit - urls.length >=0){
              emptyUrlCount = fileLimit - urls.length;
              for (let i = 0; i < emptyUrlCount; i++) {
                finalUrls.push("");
              }
            }
            let fileTypesFinal=resultFileTypes.concat(fileTypes);

            if( fileLimit - fileTypes.length >=0){
              const num = fileLimit - fileTypes.length;
              for (let i = 0; i < num; i++) {
                fileTypesFinal.push("");
              }
            }
          return {
            id:item.registrationId,
            name:item.studentName,
            requirements: ["身份证", "报名表"],
            remark:item.remark,
            fileTypes:fileTypesFinal,
            urls:finalUrls
          }
        })
        this.studentInitialData=this.students.map(item =>{
            return {
              id:item.id,
              name:item.name,
              registrationId:item.id,
              urls: item.urls,
              remark:item.remark,
              fileTypes:item.fileTypes
              }
          })
      this.showFileConfirmation=true
    },

    handleNotice(row) {
      let targetRow =null;
      // 优先获取行数据，无则取选中数据
      if(row.studentId !==undefined){
        targetRow =row
      }else{
        targetRow = this.selection;
        if (!targetRow) return this.$message.warning('请选择一个学员');
      }
      this.currentClassId=targetRow.trainingClassId
      this.noticeDialogVisible =true
    },
    handleNoticeSent() {
      // 通知发送后处理
      this.noticeDialogVisible=false
      this.getList();
    },
  },
  watch: {
    projectName(val) {
      this.$refs.tree.filter(val);
      this.getProjectTree(val);
    },
  },
};
</script>


<style scoped>
.app-container {
  display: flex;
  height: 100%;
}

.tree-panel {
  width: 360px;
  border-right: 1px solid #ebeef5;
  overflow-y: auto;
  padding: 20px;
}

.head-container {
  margin-bottom: 20px;
}

.el-form {
  margin-top: 20px;
  padding: 0 20px;
}

.el-form-item {
  margin-bottom: 10px;
}

.el-button {
  margin-right: 10px;
}

.el-table {
  margin-top: 20px;
}

.el-pagination {
  margin-top: 20px;
}
.dialog-custom {
  min-height: 500px !important;
  max-height: 600px !important;
  overflow-y: auto;
}

.group-label {
  color: #666;
  font-weight: 500;
  white-space: nowrap;
  font-size: 16px;
  margin: auto;
  margin-right: 5px;
  width: 100px; /* 固定宽度 */
  text-align: right; /* 右对齐 */
  display: inline-block;
  vertical-align: middle;
}

.el-button {
  width: 100px;
  height: 32px;
  line-height: 32px;
  padding: 0;
  text-align: center;
  font-size: 14px;
  margin-right: 8px;
}
</style>
